import network
from time import sleep


def set_ap_mode(ssid: str = "Walkline", password: str = "12345678", hidden: bool = False):
	access_point = network.WLAN(network.AP_IF)

	access_point.active(False)
	access_point.active(True)

	access_point.config(essid = ssid, password = password, hidden = hidden)

	print("\n\nWifi access point intialized:\n    ssid: %s\n    password: %s" % (ssid, password))


def set_sta_mode(ssid: str, password: str):
	status_message = {
		network.STAT_IDLE: "network idle",
		network.STAT_CONNECT_FAIL: "network connect failed",
		network.STAT_CONNECTING: "",
		network.STAT_GOT_IP: "got an ip",
		network.STAT_NO_AP_FOUND: "could not found ap",
		network.STAT_WRONG_PASSWORD: "wrong password given"
	}

	station = network.WLAN(network.STA_IF)

	station.active(False)
	station.active(True)

	print("\nConnecting to network...")

	station.connect(ssid, password)

	while (not station.isconnected()):
		result_code = station.status()

		if (result_code == network.STAT_IDLE or
			result_code == network.STAT_CONNECT_FAIL or
			result_code == network.STAT_GOT_IP or
			result_code == network.STAT_NO_AP_FOUND or
			result_code == network.STAT_WRONG_PASSWORD):
			break
		elif (result_code == network.STAT_CONNECTING):
			pass

		sleep(0.5)

	result_code = station.status()
	result_msg = status_message[result_code]

	print(result_msg)

	if (result_code == network.STAT_GOT_IP):
		ip_address = station.ifconfig()[0]

		print("network config:", station.ifconfig())
	else:
		ip_address = ""

	return result_code, result_msg, ip_address
